/**
 * Dynamicke pohlady - JavaScript
 * Zobrazenie tabulky so zoradenim, filtrami a strankovanim
 * @author Tomas Srna
 * @package bakalarka
 */

var currentAnchor = null;
var lastAnchor = "";
var pageCount = Math.ceil(itemCount / itemsPerPage);
var currentParams = new hashParams();

/**
 * Po spusteni skontrolujeme anchor 
 * a nastavime pravidelny interval kontroly
 */
$(document).ready(function() {
	// Kontrola anchoru
    checkAnchor();
    
    // Nastavenie intervalu kontroly
    setInterval("checkAnchor()", 300);
    
    // Ak mame filtre povolene, nastavime ich
    if(enableFilters)
    {
    	$('div.filters input, div.filters select').each(function (i,e) {
	    	$(e).change(function () {
    			setFilter();
    		});
    	});
    }
});

/**
 * Kontrola anchoru (cast za # v URL)
 * Pokial sa zmeni, musime data znova nacitat
 */
function checkAnchor(){  
	// Je zmena?
    if(currentAnchor == null || window.location.hash != lastAnchor) {
    	// Nastavime loader
        $("#data-loading").css("display","block");
        
        // Ziskame a sparsujeme anchor
        currentAnchor = document.location.hash;
        currentParams = new hashParams(currentAnchor);
        
        // Defaultne sme na strane 1
        if(currentParams.page == undefined)
            currentParams.page = 1;
        
        // Obnovime data
        refreshData();
        
        // Ak mame povolene filtre, musime ich obnovit
        if(enableFilters)
        	refreshFilters();
        
        // Nastavime stav posledneho anchoru
        lastAnchor = window.location.hash;
    }
}

/**
 * Kontrola filtra
 */
function checkFilterStatic() {
	if(!enableFilters)
		return;
	currentAnchor = document.location.hash;
    currentParams = new hashParams(currentAnchor);
    refreshFilters();
    lastAnchor = currentAnchor;
}

/**
 * Vyresetovanie pohladu
 */
function reset() {
	window.location.href = '#';
}

/**
 * Nastavenie filtra
 * Funkcia vytvori objekt filterParams z poloziek forumulara,
 * vytvori filter string a nastavi ho do URL
 */
function setFilter() {
	if(!enableFilters)
		return;
		
	var newFilter = new filterParams();
	$('div.filters input, div.filters select').each(function (i,e) {
		var e = $(e); 
		if(e.val() != undefined && e.val().length > 0) {
			newFilter.paramTypes.push(e.attr('name'));
			eval("newFilter."+e.attr('name')+"='"+e.val()+"'");
		}
	});
	currentParams.filter = newFilter.get();
	currentParams.page = 1;
	window.location.href = '#'+currentParams.get();
}

/**
 * Znovunacitanie dat
 */
function refreshData()
{
	// Pocas nacitania zakazeme strankovanie
	itemCount = 0;
	refreshButtons();
	
	// Nacitame data AJAXom
	$.get(dataUrl+"?"+currentParams.get(),
			function(data){
				var i = data.indexOf("}");
				// Pokial data neobsahuju JSON objekt s parametrom
				// poctu poloziek, mame tu nespravny format.
				if(i < 0)
				{
					alert(L.incorrectDataFormat);
					$("#data-loading").css("display","none");
					return;
				}
				
				// Sparsujeme JSON a z neho itemCount
				var json = data.substring(0,i+1);
				var obj = $.parseJSON(json);
				itemCount = obj.itemCount;
				
				// Teraz ked uz mame pocet poloziek, mozme nastavit tlacitka
				// na strankovanie
				refreshButtons();
				
				// Nacitame data do containera
				$('#ajax-container').html(data.substring(i+1));
				
				// Skryjeme loading
				$("#data-loading").css("display","none");
				
				// Obnovime stlpce
				refreshColumns();
		}).error(function (data) {
			// V pripade chyby ju zahlasime
			alert(L.cannotLoadView);
			$("#data-loading").css("display","none");
		});
}

/**
 * Obnovenie tlacitok na strankovanie
 */
function refreshButtons() {
	pageCount = Math.ceil(itemCount / itemsPerPage);
	$("#page-number").val(currentParams.page);
	if(currentParams.page <= 1)
		$("#page-prev").attr("disabled", "disabled");
	else
		$("#page-prev").removeAttr("disabled");
	if(currentParams.page >= pageCount)
		$("#page-next").attr("disabled", "disabled");
	else
		$("#page-next").removeAttr("disabled");
}

/**
 * Obnovenie zoradujucich stlpcov
 */
function refreshColumns() {
	$(".column-header").each(function () {
		// Odstrihneme prefix 'column-'
		var name = this.id.substring(7);
		
		// Vytvorime objekto obsahujuci nase zoradovacie pravidlo
		var localParams = new hashParams();
		localParams.by = name;
		if(currentParams.by == name && currentParams.order != 'desc')
			localParams.order = 'desc';
		if(currentParams.filter != undefined) {
			localParams.filter = currentParams.filter;
		}
		this.href = '#'+localParams.get();

		// Ak mame uz zoradenie podla nas, zobrazime sipku
		if(currentParams.by == name) {
			if(currentParams.order == 'desc') {
				$(this).next(".column-sortimage").attr('src', baseUrl+"img/bullet_arrow_down.png");
			} else {
				$(this).next(".column-sortimage").attr('src', baseUrl+"img/bullet_arrow_up.png");
			}
		} else {
			$(this).next(".column-sortimage").attr('src', baseUrl+'img/blank.gif');
		}
	});
}

/**
 * Obnova filtrov
 */
function refreshFilters() {
	if(!enableFilters)
		return;
	
	var f = $('div.filters');
	var b = $('.button-filter');
	var imgsrc = b.find('img').attr('src');
	var imgpath = imgsrc.substring(0,imgsrc.lastIndexOf('/'));
	
	// Kontrola tlacitka pre povolenie / zakazanie filtrov
	if(currentParams.filter == undefined) {
		b.find('span').html(L.enableFilters);
		b.find('img').attr('src', imgpath+'/filter.png');
		f.addClass('hidden');
	} else {
		b.find('span').html(L.disableFilters);
		b.find('img').attr('src', imgpath+'/filter_cancel.png');
		f.removeClass('hidden');
	}
	
	// Samotne parametre nacitame
	$('div.filters input, div.filters select').each(function (i,e) {
		var par = new filterParams(currentParams.filter);
		var e = $(e);
		var v = e.attr('name');
		if(eval('par.'+v) != undefined)
			e.val(eval('par.'+v));
		else
			e.val("");
	});

}

/**
 * Skok na stranku
 */
function gopage() {
	var val = $("#page-number").val();
	// Ak sme dostali cislo mimo rozsah, protestujme
	if(val < 1 || val > pageCount)
		alert(L.enterNumberBetween1And+(pageCount < 1 ? 1 : pageCount)+".");
	else {
		// Ak je to ok, zmenime parameter v hashParams
		var localParams = new hashParams(currentParams.get());
		localParams.page = val;
		window.location.href="#"+localParams.get();
	}
}

/**
 * Skok na predoslu stranku
 */
function prev() {
	next(true);
}

/**
 * Skok na dalsiu stranku
 */
function next(prev) {
	var localParams = new hashParams(currentParams.get());
	if(prev == undefined)
		++localParams.page;
	else
		--localParams.page;
	window.location.href = '#' + localParams.get();
}

/**
 * Nastavenie filtra
 */
function filter(e) {
	
	var newParams = new hashParams();
	newParams.copy(currentParams);
	if(newParams.filter == undefined) {
		newParams.filter = '[]';
	} else {
		newParams.filter = undefined;
		newParams.page = undefined;
	}
	
	window.location.href = '#'+newParams.get();
	
	if(newParams.filter != undefined)
		checkFilterStatic();
} 
